package com.hustzp.com.xichuangzhu.login;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVMobilePhoneVerifyCallback;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.RequestMobileCodeCallback;
import com.hustzp.com.xichuangzhu.R;
import com.hustzp.com.xichuangzhu.XCZBaseFragmentActivity;
import com.hustzp.com.xichuangzhu.utils.Constant;
import com.hustzp.com.xichuangzhu.utils.DialogFactory;

import org.json.JSONException;
import org.json.JSONObject;

public class SmsCodeVerifyActivity extends XCZBaseFragmentActivity {

    private EditText inputPhonenCode;
    TextView tMiddle, tRight;
    ImageView tLeftImage;
    Button sendButton;
    String intentAction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms_code_verify);
        intentAction = getIntent().getAction();
        initView();
    }

    public void initView() {
        inputPhonenCode = (EditText) findViewById(R.id.tvPhoneCode);
        tMiddle = (TextView) findViewById(R.id.middle_text);
        tRight = (TextView) findViewById(R.id.right_text);
        tRight.setVisibility(View.GONE);
        tLeftImage = (ImageView) findViewById(R.id.left_Image);
        tMiddle.setText(getResources().getString(R.string.validation_code));
        tLeftImage.setOnClickListener(viewOnclick);
        sendButton = (Button) findViewById(R.id.send_button);
        sendButton.setOnClickListener(viewOnclick);
        timeCounter.start();
        inputPhonenCode.addTextChangedListener(textWatcher);

    }

    private View.OnClickListener viewOnclick = new View.OnClickListener() {
        Dialog dialog;

        @Override
        public void onClick(View v) {
            int viewID = v.getId();
            switch (viewID) {
                case R.id.left_Image:
                    SmsCodeVerifyActivity.this.finish();
                    break;
                case R.id.send_button:
                    dialog = DialogFactory.verifyCodeMenu(SmsCodeVerifyActivity.this);
                    dialog.findViewById(R.id.video_code).setOnClickListener(viewOnclick);
                    dialog.findViewById(R.id.resend).setOnClickListener(viewOnclick);
                    break;
                case R.id.video_code:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    timeCounter.start();
                    sendVoiceCode();
                    break;
                case R.id.resend:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    timeCounter.start();

                    verifyCode();

//                    sendSmsNumber();
                    break;
            }
        }
    };
    private CountDownTimer timeCounter = new CountDownTimer(60000, 1000) {

        public void onTick(long millisUntilFinished) {
            sendButton.setEnabled(false);
            sendButton.setText(getResources().getString(R.string.wait_invalid_code) + "(" + millisUntilFinished / 1000 + ")");
        }

        public void onFinish() {
            sendButton.setText(getResources().getString(R.string.resend_invalid_code));
            sendButton.setEnabled(true);

        }
    };

    //短信验证
    private void sendSmsNumber() {

        AVUser avUser = AVUser.getCurrentUser();
        if( avUser != null){

            String currentPhoneNumber = avUser.getMobilePhoneNumber();

            boolean isHaved = currentPhoneNumber.equals(ReceiveSmsCodeActivity.phoneNumber);
            boolean  isVerify =  AVUser.getCurrentUser().isMobilePhoneVerified();
            if(isHaved && isVerify){

                DialogFactory.hintDialog(SmsCodeVerifyActivity.this, getResources().getString(R.string.number_is_registed));

                return;
            }

        }else{

        }

//
//        AVUser.verifyMobilePhoneInBackground(smsCode, new AVMobilePhoneVerifyCallback() {
//            @Override
//            public void done(AVException e) {
//                if (e != null) {
//
//                    DialogFactory.hintDialog(SmsCodeVerifyActivity.this, e.getMessage());
//                } else {
//                    AVUser.getCurrentUser().fetchInBackground(new GetCallback<AVObject>() {
//                        @Override
//                        public void done(AVObject avObject, AVException e) {
//                            startActivity(new Intent(getApplicationContext(), LaststepActivity.class));
//                        }
//                    });
//                }
//            }
//        })
    }

    //语音验证码发送
    private void sendVoiceCode() {

        AVUser avUser = AVUser.getCurrentUser();
        if( avUser != null){

            String currentPhoneNumber = avUser.getMobilePhoneNumber();

            boolean isHaved = currentPhoneNumber.equals(ReceiveSmsCodeActivity.phoneNumber);
            boolean  isVerify =  AVUser.getCurrentUser().isMobilePhoneVerified();
            if(isHaved && isVerify){

                DialogFactory.hintDialog(SmsCodeVerifyActivity.this, getResources().getString(R.string.number_is_registed));

                return;
            }

        }else{

        }

        final Dialog loading = DialogFactory.createLoadingDialog(SmsCodeVerifyActivity.this, "");
        AVOSCloud.requestVoiceCodeInBackground(ReceiveSmsCodeActivity.phoneNumber,
                new RequestMobileCodeCallback() {
                    @Override
                    public void done(AVException e) {
                        loading.dismiss();
                        if (e == null) {
                            DialogFactory.hintDialog(SmsCodeVerifyActivity.this, getResources().getString(R.string.wait_voice_verification_code));

                        } else {
                            DialogFactory.hintDialog(SmsCodeVerifyActivity.this, getResources().getString(R.string.acount_one_phonenumber_fail_wait));
                        }
                    }
                });
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 6) {
                verifyCode();
            }
        }
    };

    private void verifyCode() {

        final String code = inputPhonenCode.getText().toString().trim();
        Log.e("--code--",code);
        AVUser avUser = AVUser.getCurrentUser();
        if( avUser != null){

            String currentPhoneNumber = avUser.getMobilePhoneNumber();

            boolean isHaved = currentPhoneNumber.equals(ReceiveSmsCodeActivity.phoneNumber);
            boolean  isVerify =  AVUser.getCurrentUser().isMobilePhoneVerified();
            if(isHaved && isVerify){

                DialogFactory.hintDialog(SmsCodeVerifyActivity.this, getResources().getString(R.string.number_is_registed));

                return;
            }

        }else{

        }

        AVOSCloud.verifySMSCodeInBackground(code, ReceiveSmsCodeActivity.phoneNumber,new AVMobilePhoneVerifyCallback() {

            @Override
            public void done(AVException e) {

                Log.e("VerifyActivvity235","code:"+code+"nu:"+ ReceiveSmsCodeActivity.phoneNumber);


                if (e != null) {
                    String message = e.getMessage();
                    if(!TextUtils.isEmpty(message)){
                        try {
                            JSONObject messageObject = new JSONObject(message);
                            String code = messageObject.getString("code");
                            if("603".equals(code)){
//                                DialogFactory.hintDialog(SmsCodeVerifyActivity.this, getResources().getString(R.string.validation_code));
                                DialogFactory.hintDialog(SmsCodeVerifyActivity.this, message);
                            }
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }

//                    mSMSCode.setError(getString(R.string.error_wrong_sms_code));
                } else {

                    if (e == null) {
                        if (Constant.INTENT_ACTION_RESTPASW.equals(intentAction)) {
                            startActivity(new Intent(SmsCodeVerifyActivity.this, ResetPassWord.class));
                        } else if (Constant.INTENT_ACTION_REGISTER.equals(intentAction)) {
                            startActivity(new Intent(SmsCodeVerifyActivity.this, LaststepActivity.class));
                        } else if (Constant.INTENT_ACTION_CHGPHONE.equals(intentAction)) {
                            // 更改手机号码，重新登陆
                            startActivity(new Intent(SmsCodeVerifyActivity.this, LoginActivity.class));
                            finish();
                        }
                    }else{

                        DialogFactory.hintDialog(SmsCodeVerifyActivity.this, getResources().getString(R.string.not_validation_code));
                    }
//                    AVUser.getCurrentUser().fetchInBackground(new GetCallback<AVObject>() {
//                        @Override
//                        public void done(AVObject avObject, AVException e) {
//
//                        }
//                    });
                }

            }
        });

//        AVUser.verifyMobilePhoneInBackground(code, new AVMobilePhoneVerifyCallback() {
//
//            @Override
//            public void done(AVException e) {
//                if (e != null) {
//                    String message = e.getMessage();
//                    if(!TextUtils.isEmpty(message)){
//                        try {
//                            JSONObject messageObject = new JSONObject(message);
//                            String code = messageObject.getString("code");
//                            if("603".equals(code)){
////                                DialogFactory.hintDialog(SmsCodeVerifyActivity.this, getResources().getString(R.string.validation_code));
//                                DialogFactory.hintDialog(SmsCodeVerifyActivity.this, message);
//                            }
//                        } catch (JSONException e1) {
//                            e1.printStackTrace();
//                        }
//                    }
//
////                    mSMSCode.setError(getString(R.string.error_wrong_sms_code));
//                } else {
//                    AVUser.getCurrentUser().fetchInBackground(new GetCallback<AVObject>() {
//                        @Override
//                        public void done(AVObject avObject, AVException e) {
//                            if (e == null) {
//                                if (Constant.INTENT_ACTION_RESTPASW.equals(intentAction)) {
//                                    startActivity(new Intent(SmsCodeVerifyActivity.this, ResetPassWord.class));
//                                } else if (Constant.INTENT_ACTION_REGISTER.equals(intentAction)) {
//                                    startActivity(new Intent(SmsCodeVerifyActivity.this, LaststepActivity.class));
//                                } else if (Constant.INTENT_ACTION_CHGPHONE.equals(intentAction)) {
//                                    // 更改手机号码，重新登陆
//                                    startActivity(new Intent(SmsCodeVerifyActivity.this, LoginActivity.class));
//                                    finish();
//                                }
//                            }else{
//
//                                DialogFactory.hintDialog(SmsCodeVerifyActivity.this, getResources().getString(R.string.not_validation_code));
//                            }
//                        }
//                    });
//                }
//            }
//        });
    }


    /**
     * 判断验证码是否为 6 位纯数字，LeanCloud 统一的验证码均为 6  位纯数字。
     * @param smsCode
     * @return
     */
    public static boolean isSMSCodeValid(String smsCode) {
        String regex = "^\\d{6}$";
        return smsCode.matches(regex);
    }
}
